package com.fzdy.dataplatform.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fzdy.dataplatform.controller.api.DelSnArr;
import com.fzdy.dataplatform.controller.api.ModuleCallback;
import com.fzdy.dataplatform.controller.api.device.DeviceInfoApi;
import com.fzdy.dataplatform.controller.api.device.DevicePage;
import com.fzdy.dataplatform.controller.api.ktv.KtvListApi;
import com.fzdy.dataplatform.controller.api.sysLog.LogStringUtil;
import com.fzdy.dataplatform.controller.api.sysLog.SysLogApi;
import com.fzdy.dataplatform.core.common.AjaxCallback;
import com.fzdy.dataplatform.core.common.Check;
import com.fzdy.dataplatform.core.controller.BaseController;
import com.fzdy.dataplatform.core.vo.Seach;
import com.fzdy.dataplatform.entity.*;
import com.fzdy.dataplatform.service.*;
import com.fzdy.dataplatform.service.vo.DeviceKtvListVoService;
import com.fzdy.dataplatform.service.vo.DeviceOwnerVoService;
import com.fzdy.dataplatform.webutil.CoapUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping(value = "/sysmanage/device")
public class DeviceController extends BaseController {
    @Autowired
    private DeviceOwnerVoService deviceOwnerVoService;
    @Autowired
    private BusinessService businessService;
    @Autowired
    private NetWayService netWayService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private ProductService productService;
    @Autowired
    private DeviceKtvListVoService deviceKtvListVoService;
    @Autowired
    private DeviceOwnerService deviceOwnerService;
    @Autowired
    private CommunicationProtocolService communicationProtocolService;
    @Autowired
    private CoapUtil coapUtil;

    @RequestMapping(value = "/list")
    public String list(@RequestBody DevicePage<DeviceOwnerVo> page, HttpServletRequest request) {
        System.out.println(JSON.toJSONString(page));
        AjaxCallback ajaxCallback;
        DeviceOwnerVo device = new DeviceOwnerVo(page.getName(), 1, page.getBusinessname(), page.getProtocol(), page.getParsektv());
        if (!webUtilify.isAdmin(request)) {
            device.setUserid(webUtilify.LoginUserinfo(request).getId());
        } else {
            device.setUname(page.getUname());
        }
        deviceOwnerVoService.getPageByExampleLike(device, page);
        ajaxCallback = new AjaxCallback(page.getList(), page.getTotalRow());
        return JSON.toJSONString(ajaxCallback);
    }

    @RequestMapping(value = "/protocollist")
    public String protocolList() {
        return JSON.toJSONString(getProtocolName(communicationProtocolService.getList()));
    }

    private List getProtocolName(List<CommunicationProtocol> list) {
        List<Map<String, String>> nameList = new ArrayList<>();
        for (CommunicationProtocol protocol : list) {
            Map<String, String> name = new HashMap<>();
            name.put("name", protocol.getProtocol());
            nameList.add(name);
        }
        return nameList;
    }

    @RequestMapping(value = "/getbusinesslist")
    public String getbusinesslist(@RequestBody DeviceOwnerVo vo, HttpServletRequest request) {
        AjaxCallback ajaxCallback;
        Integer userid;
        if (!webUtilify.isAdmin(request)) {
            userid = webUtilify.LoginUserinfo(request).getId();
        } else {
            if (vo.getUserid() == null) {
                ajaxCallback = new AjaxCallback(ModuleCallback.FAILURENO, "查不到对应的业务列表");
                return JSON.toJSONString(ajaxCallback);
            }
            userid = vo.getUserid();
        }
        List<Business> businesseList = businessService.findByExampleEq(new Business(userid, 1));
        ajaxCallback = new AjaxCallback();
        ajaxCallback.setList(businesseList);
        return JSON.toJSONString(ajaxCallback);
    }

    @RequestMapping(value = "/businesslist")
    public String businesslist(HttpServletRequest request) {
        Integer userid;
        if (!webUtilify.isAdmin(request)) {
            userid = webUtilify.LoginUserinfo(request).getId();
        } else {
            userid = null;
        }
        List<Business> businesseList = businessService.findByExampleEq(new Business(userid, 1));

        List<Map<String, String>> nameList = new ArrayList<>();
        for (Business business : businesseList) {
            Map<String, String> name = new HashMap<>();
            name.put("name", business.getName());
            nameList.add(name);
        }
        System.out.println(JSON.toJSONString(nameList));
        return JSON.toJSONString(nameList);
    }


    @RequestMapping(value = "/getnetwaylist")
    public String getnetwaylist() {
        List<NetWay> list = netWayService.getList();
        AjaxCallback ajaxCallback = new AjaxCallback();
        ajaxCallback.setList(list);
        return JSON.toJSONString(ajaxCallback);
    }

    @RequestMapping(value = "/edit")
    public String edit(@RequestBody DeviceInfoApi api, HttpServletRequest request) {
        User user = webUtilify.LoginUserinfo(request);
        SysLogApi log_sysLogApi = new SysLogApi(LogStringUtil.DEVICE, LogStringUtil.SUCCESS, user.getId());
        if (api.getIsadd() == 1) {
            log_sysLogApi.setOperation(LogStringUtil.UPDATA);
        } else {
            log_sysLogApi.setOperation(LogStringUtil.ADD);
        }
        JSONObject log_content = new JSONObject();
        //sn不能为空
        AjaxCallback ajaxCallback = null;
        Business business = null;
        NetWay netWay = null;
        boolean flag = true;
        if (Check.checkStringNull(api.getSn())) {
            ajaxCallback = new AjaxCallback(ModuleCallback.FAILURENO, "sn不能为空");
            log_content.put(LogStringUtil.CAUSEFAIL, "sn不能为空");
            flag = false;
        }
        /*
         * 业务 入网方式 数据库合法性判断
         * */
        if (flag && !Check.checkObjNull(api.getBusinessid())) {
            business = businessService.get(api.getBusinessid());
            //判断数据库是否有对应的业务
            if (Check.checkObjNull(business)) {
                ajaxCallback = new AjaxCallback(ModuleCallback.FAILURENO, ModuleCallback.PARAMETERERROR);
                log_content.put(LogStringUtil.CAUSEFAIL, ModuleCallback.PARAMETERERROR);
                flag = false;
            }
        }
        if (flag && !Check.checkObjNull(api.getNetwayid())) {
            netWay = netWayService.get(api.getNetwayid());
            //判断数据库是否有对应的入网方式
            if (Check.checkObjNull(netWay)) {
                ajaxCallback = new AjaxCallback(ModuleCallback.FAILURENO, ModuleCallback.PARAMETERERROR);
                log_content.put(LogStringUtil.CAUSEFAIL, ModuleCallback.PARAMETERERROR);
                flag = false;
            }
        }
        /*
         * add为1,修改设备
         * */
        if (flag && api.getIsadd() == 1) {
            Device device = deviceService.get(api.getSn());
            if (webUtilify.isAdmin(request)) {
                if (device == null) {
                    ajaxCallback = new AjaxCallback(ModuleCallback.FAILURENO, "设备不存在");
                    log_content.put(LogStringUtil.CAUSEFAIL, "设备不存在");
                    flag = false;
                }
            } else {
                DeviceOwnerVo deviceOwner = new DeviceOwnerVo();
                deviceOwner.setUserid(user.getId());
                deviceOwner.setSn(api.getSn());
                List<DeviceOwnerVo> list = deviceOwnerVoService.findByExampleEq(deviceOwner);
                if (list.size() < 1) {
                    ajaxCallback = new AjaxCallback(ModuleCallback.FAILURENO, "找不到对应设备");
                    log_content.put(LogStringUtil.CAUSEFAIL, "找不到对应设备");
                    flag = false;
                }
            }
            if (flag) {
                log_content.put(LogStringUtil.BEFOREEDIT, JSON.toJSONString(device));
                if (business != null&&device.getBusinessid()!=null&& !device.getBusinessid().equals(api.getBusinessid())) {
                    if (business.getProduct() != null) {
                        if (business.getProduct().getCommunicationProtocol().getProtocol().contains("coap")) {
                            coapUtil.registerDevice(api.getSn(), user.getAccount(), device);
                        }
                    }else {
                        device.setCoapdeviceid(null);
                        device.setCoappsk(null);
                    }
                }
                device.GeneralParams(api.getName(), api.getImsi(), api.getImei(), api.getSim(), api.getInfo(),
                        api.getCoordinate(), api.getLocation());


                deviceSetBusinessAndparseKtv(device, business,productService);
                device.setNetway(netWay);
                deviceService.updateT(device);
                log_content.put(LogStringUtil.AFTEREDIT, JSON.toJSONString(device));
                ajaxCallback = new AjaxCallback(true, ModuleCallback.SUCCESSNO, "修改成功");
            } else {
                log_sysLogApi.setStatus(LogStringUtil.FAILURE);
            }
        }
        /*
         * add为0,添加
         * */
        else {
            if (flag) {
                //管理员不添加设备
                if (webUtilify.isAdmin(request)) {
                    ajaxCallback = new AjaxCallback(ModuleCallback.FAILURENO, "添加失败");
                    log_content.put(LogStringUtil.CAUSEFAIL, "管理员异常添加设备");
                    flag = false;
                }
                //排除重复
                Device old = deviceService.get(api.getSn());
                if (old != null) {
                    if (old.getStatus() == 1) {
                        ajaxCallback = new AjaxCallback(ModuleCallback.FAILURENO, "添加失败，sn已经存在");
                        log_content.put(LogStringUtil.CAUSEFAIL, "添加失败，sn已经存在");
                        flag = false;
                    }
                }
                if (flag) {
                    Device device;
                    if (old == null) {
                        device = new Device();
                        device.setSn(api.getSn());
                    } else {
                        device = old;
                    }
                    if (business != null) {
                        if (business.getProduct() != null) {
                            if (business.getProduct().getCommunicationProtocol().getProtocol().contains("coap")) {
                                coapUtil.registerDevice(api.getSn(), user.getAccount(), device);
                            }
                        }
                    }
                    device.GeneralParams(api.getName(), api.getImsi(), api.getImei(), api.getSim(), api.getInfo(),
                            api.getCoordinate(), api.getLocation());
                    deviceSetBusinessAndparseKtv(device, business,productService);
                    device.setNetway(netWay);
                    device.setCreatedate(new Date());
                    device.setStatus(1);
                    if (old == null) {
                        deviceService.insertT(device);
                    } else {
                        deviceService.updateT(device);
                    }
                    log_content.put("设备信息", JSON.toJSONString(device));
                    DeviceOwner deviceOwner = new DeviceOwner(device.getSn(), webUtilify.LoginUserinfo(request).getId(), 1);
                    deviceOwnerService.insertT(deviceOwner);
                    ajaxCallback = new AjaxCallback(ModuleCallback.SUCCESSNO, "添加成功");
                } else {
                    log_sysLogApi.setStatus(LogStringUtil.FAILURE);
                }
            }
        }
        log_sysLogApi.setContent(log_content);
        syslogService.WriteLog(log_sysLogApi);
        return JSON.toJSONString(ajaxCallback);
    }

    @RequestMapping(value = "/getDevice")
    public String getDevice(@RequestBody Device device) {
        device = deviceService.get(device.getSn());
        DeviceInfoApi deviceInfoApi = new DeviceInfoApi(device.getSn(), device.getName(),
                device.getImsi(), device.getImei(), device.getSim(), device.getInfo(), device.getCoordinate(),
                device.getLocation(), device.getNetwayid(), 0);
        deviceInfoApi.coapInfo(device.getCoapdeviceid(), device.getCoappsk());
        if (device.getBusiness() != null && device.getBusiness().getStatus() != 0) {
            deviceInfoApi.setBusinessid(device.getBusinessid());
            deviceInfoApi.setBusiness(device.getBusiness().getName());
        }
        if (device.getNetway() != null)
            deviceInfoApi.setNetway(device.getNetway().getName());
        AjaxCallback ajaxCallback = new AjaxCallback();
        ajaxCallback.setData(deviceInfoApi);
        return JSON.toJSONString(ajaxCallback);
    }


    @RequestMapping(value = "/del")
    public String del(@RequestBody DelSnArr delArr, HttpServletRequest request) {
        if (webUtilify.isAdmin(request)) {
            deviceService.batchDelete(delArr.getIds());
        } else {
            deviceService.batchDelete(delArr.getIds(), webUtilify.LoginUserinfo(request).getId());
        }
        JSONObject log_content = new JSONObject();
        log_content.put("id", JSON.toJSONString(delArr.getIds()));
        syslogService.WriteLog(new SysLogApi(LogStringUtil.DEL, LogStringUtil.PRIVATEPROTOCOL, LogStringUtil.SUCCESS,
                log_content, webUtilify.LoginUserinfo(request).getId()));
        AjaxCallback ajaxCallback = new AjaxCallback(ModuleCallback.SUCCESSNO, "删除成功");
        return JSON.toJSONString(ajaxCallback);
    }


    @RequestMapping(value = "/getKtvListBySn")
    public String getKtvListBySn(@RequestBody Seach seach, HttpServletRequest request) {
        AjaxCallback ajaxCallback;
        if (Check.checkStringNull(seach.getSn())) {
            ajaxCallback = new AjaxCallback(ModuleCallback.FAILURENO, ModuleCallback.PARAMETERERROR);
        } else {
            Device device = deviceService.get(seach.getSn());
            if (Check.checkObjNull(device)) {
                ajaxCallback = new AjaxCallback(ModuleCallback.FAILURENO, ModuleCallback.PARAMETERERROR);
            } else {
                if (!webUtilify.isAdmin(request) && !device.getDeviceOwner().getUserid()
                        .equals(webUtilify.LoginUserinfo(request).getId())) {
                    ajaxCallback = new AjaxCallback(ModuleCallback.FAILURENO, ModuleCallback.PARAMETERERROR);
                } else {
                    DeviceKtvListVo vo = new DeviceKtvListVo();
                    vo.setSn(seach.getSn());
                    List<DeviceKtvListVo> list = deviceKtvListVoService.findByExampleEq(vo, "seq");
                    List<KtvListApi> apis = new ArrayList<>();
                    for (DeviceKtvListVo deviceKtvListVo : list) {
                        KtvListApi api = new KtvListApi(deviceKtvListVo.getSeq(), deviceKtvListVo.getName(), deviceKtvListVo.getTid());
                        apis.add(api);
                    }
                    ajaxCallback = new AjaxCallback();
                    ajaxCallback.setList(apis);
                }
            }
        }
        return JSON.toJSONString(ajaxCallback);
    }

    public static void deviceSetBusinessAndparseKtv(Device device, Business business, ProductService productService) {
        device.setBusiness(business);
        if (business != null) {
            Integer pid = business.getProductid();
            Product product = productService.get(pid);
            if (product != null && product.getCommunicationProtocol() != null && (product.getCommunicationProtocol().
                    getProtocol() != null)
                    && product.getCommunicationProtocol().getProtocol().contains("ktv")) {
                device.setPrivateProtocol(1);
            } else {
                device.setPrivateProtocol(0);
            }
        }
    }


}
